<?php
header("Access-Control-Allow-Origin:*");
/* 短消息的标志 */
define('MSG_SYSTEM' , 0); //系统消息
/**
 *
 * 消息列表 MessageList
 * @param unknown_type $pars
 */

function MessageList($pars){
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$row=$pars->row?$pars->row:0;
		$size=$pars->size?$pars->size:10;

		$list = get_list($pars->uid, $row,$size, 'newpm');

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 *
 * 消息明细 MessageList
 * @param unknown_type $pars
 */

function MessageView($pars){
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$list = get($pars->uid, $pars->msg_id);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 *
 * 消息明细 MessageList
 * @param unknown_type $pars
 */

function MessageDrop($pars){
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$model_message =& m('message');
			
		$msg_id=$pars->msg_id;
		$msg_ids = is_array($msg_id) ? $msg_id : explode(',', $msg_id);
		$user_id=$pars->uid;

		if (!$msg_ids)
		{
			throw new Exception('没有要删除的消息');
		}
		if (!$user_id)
		{
			throw new Exception('用户不存在');
		}
		$drop_ids=array();
		foreach ($msg_ids as $msg_id)
		{
			$message = $model_message->get_info($msg_id);
			if($message){
				if ($message['from_id'] == MSG_SYSTEM && $message['to_id'] == $user_id)
				{
					$drop_ids[] = $msg_id; // 删除系统发给自己的消息
				}
				elseif ($user_id==$message['to_id']) //收件箱
				{
					if ($message['status']==2 || $message['status']==3)
					{
						$model_message->edit($msg_id, array('status' => 2));
					}else
					{
						$drop_ids[] = $msg_id; //记录需要删除记录的msg_id
					}
				}
				elseif ($user_id==$message['from_id']) //发件箱
				{
					if ($message['status']==1 || $message['status']==3)
					{
						$model_message->edit($msg_id, array('status' => 1));
					}else
					{
						$drop_ids[] = $msg_id; //记录需要删除记录的msg_id
					}
				}
				else
				{
					throw new Exception('你不能删除这条短信');
				}
			}else{
				throw new Exception('你不能删除这条短信');
			}
		}
		if ($drop_ids){
			$model_message->drop($drop_ids);
		}

		$list="删除成功";
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}



/**
 *    获取短消息内容
 *
 *    @author    Garbin
 *    @param     int  $user_id  拥有者
 *    @param     int  $pm_id    短消息标识
 *    @param     bool $full     是否包括回复 false:不包括 true包括
 *    @return    false:没有消息 array:消息内容
 */
function get($user_id, $pm_id)
{
	$model_message =& m('message');
	$topic = $model_message->get(array(
            'fields'     => 'this.*',
            'conditions' => 'msg_id=' . $pm_id . ' AND parent_id=0 AND ((status IN (1,3) AND to_id = ' . $user_id . ') OR (status IN (2,3) AND from_id = ' . $user_id . '))',
	));
	if (empty($topic))
	{
		throw new Exception("消息不存在");
	}
	if ($topic['from_id'] == MSG_SYSTEM)
	{
		$topic['user_name'] = "系统消息";
		$topic['system'] = 1;
	}
	$topic['add_time']=local_date('Y-m-d H:i',$topic['add_time']);
	$topic['last_update']=local_date('Y-m-d H:i',$topic['last_update']);
	if($topic['type']!="订单"){
		//$topic['content']=SITE_URL."index.php?app=message&act=view&msg_id=".$topic['msg_id'];
	}
	$topic['new'] = (($topic['from_id'] == $user_id && $topic['new'] == 2)||($topic['to_id'] == $user_id && $topic['new'] == 1 )) ? 1 : 0;

	!empty($topic['new']) && $model_message->edit($pm_id, array(
            'new'   => 0,
	)); //标示已读

	//$topic['portrait'] = portrait($topic['from_id'], $topic['portrait']);
	$replies = $model_message->find(array(
                'fields'     => 'this.*',
                'conditions' => 'parent_id=' . $pm_id,
	));
	$topic['replies']=$replies;
	return $topic;
}
/**
 *    获取消息列表
 *
 *    @author    Garbin
 *    @param     int    $user_id
 *    @param     string $limit
 *    @param     string $folder 可选值:inbox, outbox
 *    @return    array:消息列表
 */
function get_list($user_id, $row,$size, $folder = 'privatepm')
{
	$limit = $row.','.$size;
	$condition = '';
	switch ($folder)
	{
		case 'privatepm':
			$condition = '((from_id = ' . $user_id . ' AND status IN (2,3)) OR (to_id = ' . $user_id . ' AND status IN (1,3)) AND from_id > 0)';
			break;
		case 'systempm':
			$condition = 'from_id = ' . MSG_SYSTEM . ' AND to_id = ' . $user_id;
			break;
		case 'announcepm':
			$condition = 'from_id = 0 AND to_id = 0';
			break;
		default:
			$condition = '((from_id = ' . $user_id . ' AND status IN (2,3)) OR (to_id = ' . $user_id . ' AND status IN (1,3)) AND from_id > 0) or (from_id = ' . MSG_SYSTEM . ' AND to_id = ' . $user_id.') or (from_id = 0 AND to_id = 0)';
			//$condition = '((new = 1 AND status IN (1,3) AND to_id = ' . $user_id . ') OR (new =2 AND status IN (2,3) AND from_id = ' . $user_id . ') or (from_id = ' . MSG_SYSTEM . ' AND to_id = ' . $user_id.'))';
			//$condition = '((new = 1 AND status IN (1,3) AND to_id = ' . $user_id . ') OR (new =2 AND status IN (2,3) AND from_id = ' . $user_id . '))';
			break;
	}
	$model_message =& m('message');
	$messages = $model_message->find(array(
            'fields'        =>'this.*',
            'conditions'    =>  $condition .' AND parent_id=0 ',
            'count'         => true,
            'limit'         => $limit,
            'order'         => 'new desc, last_update DESC',
	));
	$subject = '';
	if (!empty($messages))
	{
		foreach ($messages as $key => $message)
		{
			$messages[$key]['new'] = (($message['from_id'] == $user_id && $message['new'] == 2)||($message['to_id'] == $user_id && $message['new'] == 1 )) ? 1 : 0; //判断是否是新消息
			$subject = removecode($messages[$key]['content']);
			$messages[$key]['content'] = htmlspecialchars($subject);
			$message['from_id'] == MSG_SYSTEM && $messages[$key]['user_name'] = "系统消息"; //判断是否是系统消息
			$messages[$key]['add_time']=local_date('Y-m-d H:i',$message['add_time']);
			$messages[$key]['last_update']=local_date('Y-m-d H:i',$message['last_update']);
		}
	}
	return array_values($messages);
}

function removecode($str) {
	$rs = trim(preg_replace(array(
            "/\[(img)=?.*\].*?\[\/(img)\]/siU",
            "/\[\/?(url)=?.*\]/siU",
            "/\r\n/",
	), '', $str));
	return $rs;
}

/**
 *
 * 消息发送 messagesend
 *    @param     int $sender        发送者
 *    @param     array $recipient     接收者
 *    @param     string $subject    标题
 *    @param     string $message    内容
 *    @param     int $replyto       回复主题
 *    @return    false:失败   true:成功
 */
function send($sender, $recipient, $subject, $message, $replyto = 0,$getui=false,$type="消息"){
	$model_message =& m('message');
	$msg_id = $model_message->send($sender, $recipient, $subject, $message, $replyto,$type);
	if (!$msg_id)
	{
		return 0;
	}
	//推送
	if($getui){
		$tocid = $model_message->getRow("select igetui,device from yk_member where user_id=".$recipient);
		if($getui=='user'){
			//推送消息
			if(!empty($tocid)){
					
				header("Content-Type: text/html; charset=utf-8");
				require_once(ROOT_PATH . '/service/gt/' . 'IGt.Push.php');
					
				$igt = new IGeTui(IGETUIHOST,IGETUIAPPKEY,IGETUIMASTERSECRET);
				//$igt = new IGeTui('',APPKEY,MASTERSECRET);//此方式可通过获取服务端地址列表判断最快域名后进行消息推送，每10分钟检查一次最快域名
					
				//消息模版：
				// 1.TransmissionTemplate:透传功能模板
				// 2.LinkTemplate:通知打开链接功能模板
				// 3.NotificationTemplate：通知透传功能模板
				// 4.NotyPopLoadTemplate：通知弹框下载功能模板
				$template =  new IGtTransmissionTemplate();
				$template->set_appId(IGETUIAPPID);//应用appid
				$template->set_appkey(IGETUIAPPKEY);//应用appkey
				$template->set_transmissionType(0);//透传消息类型1
				$template->set_transmissionContent($msg_id);//透传内容
				if($tocid['device']!='android'){
					$template->set_pushInfo("", 1, $message, "", "", "", "", "");
				}
				//个推信息体
				$message = new IGtSingleMessage();
				$message->set_isOffline(true); //是否离线
				$message->set_offlineExpireTime(3600*12*1000); //离线时间
				$message->set_data($template); //设置推送消息类型
				$message->set_PushNetWorkType(0); //设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送
				//接收方
				$target = new IGtTarget();
				$target->set_appId(IGETUIAPPID);
				$target->set_clientId($tocid['igetui']);
				$rep = $igt->pushMessageToSingle($message,$target);
			}
		}
		else{
			//推送消息
			if(!empty($tocid)){
					
				header("Content-Type: text/html; charset=utf-8");
				require_once(ROOT_PATH . '/service/gt/' . 'IGt.Push.php');
					
				$igt = new IGeTui(CARIGETUIHOST,CARIGETUIAPPKEY,CARIGETUIMASTERSECRET);
				//$igt = new IGeTui('',APPKEY,MASTERSECRET);//此方式可通过获取服务端地址列表判断最快域名后进行消息推送，每10分钟检查一次最快域名
					
				//消息模版：
				// 1.TransmissionTemplate:透传功能模板
				// 2.LinkTemplate:通知打开链接功能模板
				// 3.NotificationTemplate：通知透传功能模板
				// 4.NotyPopLoadTemplate：通知弹框下载功能模板
				$template =  new IGtTransmissionTemplate();
				$template->set_appId(CARIGETUIAPPID);//应用appid
				$template->set_appkey(CARIGETUIAPPKEY);//应用appkey
				$template->set_transmissionType(0);//透传消息类型1
				$template->set_transmissionContent($msg_id);//透传内容
				if($tocid['device']!='android'){
					$template->set_pushInfo("", 1, $message, "", "", "", "", "");
				}
				//个推信息体
				$message = new IGtSingleMessage();
				$message->set_isOffline(true); //是否离线
				$message->set_offlineExpireTime(3600*12*1000); //离线时间
				$message->set_data($template); //设置推送消息类型
				$message->set_PushNetWorkType(0); //设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送
				//接收方
				$target = new IGtTarget();
				$target->set_appId(CARIGETUIAPPID);
				$target->set_clientId($tocid['igetui']);
				$rep = $igt->pushMessageToSingle($message,$target);
			}
		}
	}
	return $msg_id;
}

/**
 * ios发送消息
 * @param unknown_type $sender
 * @param unknown_type $recipient
 * @param unknown_type $subject
 * @param unknown_type $message
 * @param unknown_type $replyto
 * @param unknown_type $getui
 * @param unknown_type $type
 * @throws Exception
 */
function sendIOS($sender, $recipient, $subject, $message, $replyto = 0,$getui=false,$type="消息"){
	$model_message =& m('message');
	$msg_id = $model_message->send($sender, $recipient, $subject, $message, $replyto,$type);
	if (!$msg_id)
	{
		return 0;
	}
	//推送
	if($getui){
		$tocid = $model_message->getOne("select igetui from yk_member where user_id=".$recipient);
		if($getui=='user'){
			//推送消息
			if(!empty($tocid)){
					
				header("Content-Type: text/html; charset=utf-8");
				require_once(ROOT_PATH . '/service/gt/' . 'IGt.Push.php');

				$igt = new IGeTui(IGETUIHOST_IOS,IGETUIAPPKEY_IOS,IGETUIMASTERSECRET_IOS);
				$template = new IGtAPNTemplate();
				$template->set_pushInfo("启动", 1, $subject, "", $message, "", "", "");


				//单个用户推送接口
				$message = new IGtSingleMessage();
				$message->set_data($template);
				$ret = $igt->pushAPNMessageToSingle($tocid, DEVICETOKEN, $message);
			}
		}
		else{
			//推送消息
			if(!empty($tocid)){
					
				header("Content-Type: text/html; charset=utf-8");
				require_once(ROOT_PATH . '/service/gt/' . 'IGt.Push.php');
					
				$igt = new IGeTui(CARIGETUIHOST_IOS,CARIGETUIAPPKEY_IOS,CARIGETUIMASTERSECRET_IOS);
				$template = new IGtAPNTemplate();
				$template->set_pushInfo("启动", 1, $subject, "", $message, "", "", "");

				//单个用户推送接口
				$message = new IGtSingleMessage();
				$message->set_data($template);
				$ret = $igt->pushAPNMessageToSingle($tocid, DEVICETOKEN, $message);
			}
		}
	}
	return $msg_id;
}

/**
 *
 * 消息发送 messagesend
 *    @param     int $sender        发送者
 *    @param     array $recipient     接收者
 *    @param     string $subject    标题
 *    @param     string $message    内容
 *    @param     int $replyto       回复主题
 *    @return    false:失败   true:成功
 */

function messagesend($sender, $recipient, $subject, $message, $replyto = 0){
	$status=0;
	try{

		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		if(empty($pars->recipient)){
			throw new Exception('接收人员不存在');
		}

		if(empty($pars->subject)){
			throw new Exception('标题不存在');
		}

		if(empty($pars->message)){
			throw new Exception('内容不存在');
		}
		$msg_id=send($pars->uid,$pars->recipient,$pars->subject,$pars->message,$pars->replyto);
		$list=array('msg_id'=>$msg_id);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


?>